package cn.edu.cdut.contentproviderdemo1;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.eliza.ascl.conpv.R;

public class P1MainActivity extends AppCompatActivity {

    TextView mContactTV;
    EditText username;
    EditText phone;

    String mSelectionClause;
    String[] mSelectionArgs;

    String[] SQL_COLUMN = new String[]{
            ContactsContract.CommonDataKinds.Identity.RAW_CONTACT_ID,//raw_contact_id
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,//display_name
            ContactsContract.CommonDataKinds.Phone.NUMBER//data1
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_p1);

        mContactTV = findViewById(R.id.ContactTV);
        username = findViewById(R.id.text1);
        phone = findViewById(R.id.text2);

        if(Build.VERSION.SDK_INT >= 23){
            String[] permissions = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS};
            int i = 0;
            for (String permission : permissions){
                if(this.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED){
                    this.requestPermissions(permissions,i++);
                }
            }
        }


    }

    public void queryClick(View view){
        String name = username.getText().toString();
        if(!name.equals("")){
            Cursor cursor = getContact(name);
            printQueryResult(cursor);
        }
    }

    private Cursor getContact(String mSearchString){
        mSelectionClause = ContactsContract.Contacts.DISPLAY_NAME + "=?";
        mSelectionArgs = new String[]{mSearchString};
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                SQL_COLUMN,mSelectionClause,mSelectionArgs,null);
        return cursor;
    }



    public void insertClick(View view){
        String name = username.getText().toString();
        String phoneNum = phone.getText().toString();

        ContentValues values = new ContentValues();
        Uri rawContentUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI,values);
        long rawContentId = ContentUris.parseId(rawContentUri);

        if(!name.equals("")){
            values.clear();
            values.put(ContactsContract.Data.RAW_CONTACT_ID,rawContentId);
            values.put(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,name);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);
        }

        if(!phoneNum.equals("")){
            values.clear();
            values.put(ContactsContract.Data.RAW_CONTACT_ID,rawContentId);
            values.put(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            values.put(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
            values.put(ContactsContract.CommonDataKinds.Phone.NUMBER,phoneNum);
            getContentResolver().insert(ContactsContract.Data.CONTENT_URI,values);

        }
        /*
        values.put("raw_contact_id",rawContentId);
        values.put("mimetype","vnd.android.cursor.item/phone_v2");
        values.put("data1",phoneNum);
        values.put("data2","2");
        //content://com.android.contacts/data/
         */




    }

    public void deleteClick(View view){
        String name = username.getText().toString();
        if(!name.equals("")){
            getContentResolver().delete(ContactsContract.RawContacts.CONTENT_URI,ContactsContract.Contacts.DISPLAY_NAME+"=?",new String[]{name});
        }
    }

    public void updateClick(View view){
        String name = username.getText().toString();
        String phoneNum = phone.getText().toString();

        Long rawContactId = 0L;
        Uri uri = Uri.parse("content://com.android.contacts/data");
        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues();
        values.put("data1",phoneNum);


        if(!name.equals("")){
            Cursor cursor = getContact(name);

            if(cursor.moveToFirst()){
                rawContactId =  cursor.getLong(0);
            }
            resolver.update(uri,values," mimetype=? and raw_contact_id = ?",new String[]{ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,rawContactId+""});
            cursor.close();
        }
    }

    public void queryAll(View view){
        //content://com.android.contacts/data/phones

        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,SQL_COLUMN,null,null,null);
        printQueryResult(cursor);

    }

    private void printQueryResult(Cursor cursor){
        if(cursor != null){
            mContactTV.setText("");
            while (cursor.moveToNext()){
                String ID = cursor.getString(0);
                String contactName = cursor.getString(1);
                String phoneNumber = cursor.getString(2);
                mContactTV.append("联系人ID："+ID+"\n联系人姓名："+contactName+"    联系人电话："+phoneNumber+"\n");
            }
        }
        cursor.close();
    }
}
